package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.CameraDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Camera;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CameraService extends LogicService<CameraDao, Camera, Long> {

    private final PropertyService propertyService;
    public CameraService(@Autowired CameraDao dao,PropertyService propertyService) {
        super(dao);
        this.propertyService = propertyService;
    }
    @Value("${camera.captureUrl}")
    private String captureUrl;

    @Value("${camera.access_token}")
    private String accessToken;

    @Value("${camera.imageCounter}")
    private int imageCounter;

    @Transactional
    public void saveCameraPhoto(String photo, Device device){
        Camera camera = new Camera();
        camera.setPhoto(photo);
        camera.setDevice(device);
        dao.save(camera);
    }
    public List<String> getAllPhotos() {
        List<Camera> cameras = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<String> photoPaths = new ArrayList<>();
        String prefixToRemove = "D:\\wwy\\headend\\"; // 定义要移除的前缀

        for (Camera c : cameras) {
            String photoPath = c.getPhoto();
            // 移除前缀
            String modifiedPhotoPath = photoPath.replace(prefixToRemove, "");
            photoPaths.add(modifiedPhotoPath);
        }
        return photoPaths;
    }
    // 获取图片的 URL
    public String getPictureUrl(String deviceSerialNumber,int quality){
        int channelNo = 1;
        if(quality < 0 || quality > 4){
             throw new IllegalArgumentException("Quality must be between 0 and 4.");
        }
        return fetchPictureUrl(accessToken, deviceSerialNumber, channelNo, quality);
    }

    private String fetchPictureUrl(String accessToken, String deviceSerial, int channelNo, int quality) {
        String url = captureUrl;
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求参数
        LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("accessToken", accessToken);
        requestBody.add("deviceSerial", deviceSerial);
        requestBody.add("channelNo", String.valueOf(channelNo));
        requestBody.add("quality", String.valueOf(quality));

        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<LinkedMultiValueMap<String, String>> entity = new HttpEntity<>(requestBody, headers);

        // 使用 ParameterizedTypeReference 来明确指定返回类型
        ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                new ParameterizedTypeReference<>() {} // 这里明确指定返回类型
        );

        // 解析响应数据
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            System.out.println(responseBody);
            if (responseBody != null && responseBody.containsKey("data")) {
                Object dataObject = responseBody.get("data");
                if (dataObject instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, String> data = (Map<String, String>) dataObject;
                    return data.get("picUrl");
                } else {
                    throw new RuntimeException("Data field is not of expected Map type.");
                }
            } else {
                throw new RuntimeException("Failed to get the picture URL.");
            }
        } else {
            throw new RuntimeException("Failed to fetch picture URL.");
        }
    }

    public String downloadImage(String imageUrl, String filePath) throws IOException {
        // 下载图片并保存到本地
        URL url = new URL(imageUrl);
        String originalFileName = Paths.get(url.getPath()).getFileName().toString();
        String fileExtension = "";
        int dotIndex = originalFileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < originalFileName.length() - 1) {
            fileExtension = originalFileName.substring(dotIndex);
        }
        // 生成新的文件名，包含编号
        String fileName = "image_" + imageCounter + fileExtension;
        Path targetPath = Paths.get(filePath, fileName);
        Files.createDirectories(targetPath.getParent());
        try (InputStream in = url.openStream()) {
            Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
        }
        imageCounter++;        Map<String, String> properties = propertyService.getProperties();
        properties.put("camera.imageCounter", String.valueOf(imageCounter));
        propertyService.writeProperties(properties);
        return targetPath.toString();
    }
}
